<template>
  <div class="page-container" v-global-loading="loading">
    <div class="page-card-container">
      <a-form :model="pageSet" layout="inline">
        <a-form-item label="位置名称">
          <a-input
            v-model:value="pageSet.positionName"
            style="width: 170px"
            :allowClear="true"
          ></a-input>
        </a-form-item>
        <a-form-item label="位置类型">
          <a-select
            v-model:value="pageSet.positionType"
            style="width: 180px"
            allowClear
          >
            <a-select-option :value="item.value" v-for="item in positionType">{{
              item.label
            }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="">
          <div class="commonBtn-warning" @click="loadPagination(true)">
            查询
          </div>
        </a-form-item>
        <a-form-item label="">
          <div class="commonBtn-primary" @click="reset">重置</div>
        </a-form-item>
        <a-form-item label="">
          <div class="commonBtn-primary" @click="operation(1)">新建</div>
        </a-form-item>
      </a-form>
      <a-table
        size="small"
        :loading="tableLoading"
        :dataSource="tableData"
        :columns="columns"
        bordered
        :pagination="false"
        :scroll="{
          x: 1200,
          y: useAppStore.pageCommonInfo.canUseHeight - 36 + 'px'
        }"
      >
        <template #bodyCell="{text, record, index, column}">
          <template v-if="column.title == '操作'">
            <span
              class="pointer c-primaryColor"
              onselectstart="return false"
              @click="operation(3, record)"
              >&nbsp; 编辑</span
            >
            <span
              class="pointer c-primaryColor"
              onselectstart="return false"
              @click="operation(4, record)"
              >&nbsp; 删除</span
            >
            <span
              class="pointer c-primaryColor"
              onselectstart="return false"
              @click="operation(5, record)"
              >&nbsp; {{ record.status == 1 ? "停用" : "启用" }}</span
            >
          </template>
          <template v-if="column.title == '展示图片'">
            <div
              v-if="
                record.positionType != 7 &&
                record.positionType != 8 &&
                record.positionType != 3
              "
            >
              <div
                class="pointer"
                v-if="text"
                @click="
                  () => {
                    setVisible(true, index);
                  }
                "
              >
                <img :src="text" alt="" style="height: 30px" />
                <a-image
                  :width="0"
                  :style="{display: 'none'}"
                  :preview="{
                    visible: visibleImg[index],
                    onVisibleChange: (e) => {
                      setVisible(e, index);
                    }
                  }"
                  :src="text"
                />
              </div>
            </div>
            <div v-else>
              <div
                class="pointer"
                v-if="record.imgs.length && record.imgs"
                @click="
                  () => {
                    setVisible(true, index);
                  }
                "
              >
                <img :src="record.imgs[0].url" alt="" style="height: 30px" />
                <a-image
                  :width="0"
                  :style="{display: 'none'}"
                  :preview="{
                    visible: visibleImg[index],
                    onVisibleChange: (e) => {
                      setVisible(e, index);
                    }
                  }"
                  :src="record.imgs[0].url"
                />
              </div>
            </div>
          </template>
        </template>
      </a-table>
      <Pagination
        :pageSet="pageSet"
        style="margin-top: 10px"
        :loadPagination="loadPagination"
      ></Pagination>
      <a-modal
        v-model:open="visible"
        width="800px"
        :title="title"
        :footer="null"
        :maskClosable="false"
        @cancel="operation(6)"
      >
        <div v-global-loading="modalloading">
          <a-form :labelCol="{span: 6}" :model="form" ref="formRef">
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item
                  label="位置名称"
                  name="positionName"
                  :rules="[{required: true, message: '请填写'}]"
                >
                  <a-input v-model:value="form.positionName" />
                </a-form-item>
                <a-form-item
                  label="位置类型"
                  name="positionType"
                  :rules="[{required: true, message: '请填写'}]"
                >
                  <a-select
                    v-model:value="form.positionType"
                    style="width: 100%"
                    @change="
                      () => {
                        form.imgs = [];
                        getColumnsImgs();
                      }
                    "
                  >
                    <a-select-option
                      :value="item.value"
                      v-for="item in positionType"
                      >{{ item.label }}</a-select-option
                    >
                  </a-select>
                </a-form-item>
                <a-form-item label="状态" name="status">
                  <a-radio-group v-model:value="form.status" name="status">
                    <a-radio :value="1">启用</a-radio>
                    <a-radio :value="0">停用</a-radio>
                  </a-radio-group>
                </a-form-item>
                <a-form-item
                  label="说明"
                  name="description"
                  v-if="
                    form.positionType != 7 &&
                    form.positionType != 8 &&
                    form.positionType != 3
                  "
                >
                  <a-input v-model:value="form.description" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item
                  label="时间区间"
                  name="date"
                  v-if="!form.isPermanent"
                  :rules="[{required: true, message: '请填写'}]"
                >
                  <a-range-picker
                    v-model:value="form.date"
                    value-format="YYYY-MM-DD"
                    format="YYYY-MM-DD"
                    @change="changePicker"
                  />
                </a-form-item>
                <a-form-item
                  label="是否永久"
                  name="isPermanent"
                  v-if="form.positionType != 4"
                >
                  <a-radio-group
                    v-model:value="form.isPermanent"
                    name="isPermanent"
                  >
                    <a-radio :value="true">是</a-radio>
                    <a-radio :value="false">否</a-radio>
                  </a-radio-group>
                </a-form-item>
                <a-form-item
                  label="说明"
                  name="description"
                  v-if="
                    form.positionType == 7 ||
                    form.positionType == 8 ||
                    form.positionType == 3
                  "
                >
                  <a-input v-model:value="form.description" />
                </a-form-item>
                <a-form-item
                  label="展示图片"
                  name="img"
                  v-if="
                    form.positionType != 7 &&
                    form.positionType != 8 &&
                    form.positionType != 3
                  "
                >
                  <div
                    style="
                      width: 100px;
                      height: 100px;
                      border: 1px solid rgb(211, 211, 211);
                      border-radius: 10px;
                      display: flex;
                      justify-content: center;
                      align-items: center;
                      cursor: pointer;
                    "
                    v-if="!form.img"
                    @click="upload"
                  >
                    <CloudUploadOutlined
                      style="color: rgb(214, 208, 208); font-size: 60px"
                    />
                  </div>
                  <img
                    :src="form.img"
                    @click="upload"
                    style="width: 200px; cursor: pointer"
                    alt=""
                    v-else
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <div
              v-if="
                form.positionType == 7 ||
                form.positionType == 8 ||
                form.positionType == 3
              "
            >
              <div
                style="
                  display: flex;
                  justify-content: end;
                  margin: -10px 10px 2px 0px;
                "
                v-if="form.positionType == 8"
              >
                <a-button
                  type="primary"
                  @click="addImgs"
                  v-if="form.imgs.length < 1"
                  >添加</a-button
                >
              </div>
              <div
                style="
                  display: flex;
                  justify-content: end;
                  margin: -10px 10px 2px 0px;
                "
                v-else
              >
                <a-button type="primary" @click="addImgs">添加</a-button>
              </div>
              <a-table
                size="small"
                :dataSource="form.imgs"
                :columns="columnsImgs"
                bordered
                :pagination="false"
                @change="handleChange"
              >
                <template #bodyCell="{text, record, index, column}">
                  <template v-if="column.title == '展示图片'">
                    <div style="display: flex; justify-content: center">
                      <div
                        style="
                          width: 50px;
                          height: 50px;
                          border: 1px solid rgb(211, 211, 211);
                          border-radius: 10px;
                          display: flex;
                          justify-content: center;
                          align-items: center;
                          cursor: pointer;
                        "
                        v-if="!text"
                        @click="uploadImgs(index)"
                      >
                        <CloudUploadOutlined
                          style="color: rgb(214, 208, 208); font-size: 30px"
                        />
                      </div>
                      <img
                        :src="text"
                        @click="uploadImgs(index)"
                        style="height: 50px; cursor: pointer"
                        alt=""
                        v-else
                      />
                    </div>
                  </template>
                  <template v-if="column.title == '图片跳转地址'">
                    <a-input v-model:value="form.imgs[index].linkUrl"></a-input>
                  </template>
                  <template v-if="column.title == '排序'">
                    <a-input-number
                      v-model:value="form.imgs[index].sort"
                      :controls="false"
                      @pressEnter="sortRank"
                      @blur="sortRank"
                    ></a-input-number>
                  </template>
                  <template v-if="column.title == '操作'">
                    <span
                      style="color: red; cursor: pointer"
                      @click="operationDel(index)"
                      >删除</span
                    >
                  </template>
                </template>
              </a-table>
            </div>
            <div v-if="form.positionType == 5 || form.positionType == 9">
              <div style="font-size: 16px; font-weight: 600">请选择标签:</div>
              <div
                style="display: flex; justify-content: end; margin-bottom: 10px"
              >
                <a-input-search
                  allowClear
                  v-model:value="pageSet1.name"
                  placeholder="请输入标签名称"
                  enter-button
                  @search="loadPagination1(true)"
                  style="width: 300px"
                />
              </div>
              <a-table
                size="small"
                :loading="tableLoading1"
                :dataSource="tableData1"
                :columns="columns1"
                bordered
                :pagination="false"
                row-key="id"
                :row-selection="{
                  selectedRowKeys: form.tagsIds,
                  onChange: onSelectChange,
                  preserveSelectedRowKeys: true
                }"
                :scroll="{x: 700, y: 500}"
              ></a-table>
              <Pagination
                :pageSet="pageSet1"
                style="margin-top: 10px"
                :loadPagination="loadPagination1"
              ></Pagination>
            </div>
          </a-form>
          <div style="display: flex; justify-content: end; margin-top: 6px">
            <a-button style="margin-right: 14px" @click="operation(6)"
              >取消</a-button
            >
            <a-button type="primary" @click="operation(2)">确定</a-button>
          </div>
        </div>
      </a-modal>
    </div>
  </div>
</template>
<script lang="ts" setup>
import {ref, inject, onActivated, onMounted, nextTick, computed} from "vue";
import {
  positionConfigCreate,
  positionConfigUpdate,
  positionConfigDelete,
  positionConfigDetail,
  positionConfigPage,
  positionConfigList,
  positionConfigChangeStatus,
  checkDuplicateSpecialOffer,
  positionConfigSetTag
} from "@/api/merchandise/operatingSystem";
import {tagsInfoPage} from "@/api/customerArchives/memberTag";
import useAppStore from "@/store/app";
import {trigerUpload, trigerUploadObs} from "@/utils/common";
import Pagination from "@/components/pagination/Pagination.vue";
import {message, Modal} from "ant-design-vue";
import dayjs from "dayjs";
import {TableProps} from "ant-design-vue";
const calcCanUseHeight: any = inject("calcCanUseHeight");
onActivated(() => {
  calcCanUseHeight();
});
onMounted(() => {
  calcCanUseHeight();
});
const visibleImg = ref<any>([]);
const setVisible = (flag, index) => {
  visibleImg.value[index] = flag;
};
const loading = ref(false);
const tableLoading = ref(false);
const tableData = ref([]);
const visible = ref(false);
const title = ref("新建");
const form = ref<any>({});
const formRef = ref();
const modalloading = ref(false);
const pageSet = ref<any>({
  pageNo: 1,
  pageSize: 20,
  total: 0
});
const upload = async () => {
  const fileInfo: any = await trigerUpload();
  let files = fileInfo.target.files[0];
  if (
    files.type == "image/jpeg" ||
    files.type == "image/png" ||
    files.type == "image/jpg"
  ) {
    modalloading.value = true;
    trigerUploadObs(fileInfo)
      .then((res) => {
        form.value.img = res;
      })
      .finally(() => {
        modalloading.value = false;
      });
  } else {
    message.error("请上传jpeg、png、jpg类型的图片");
  }
};
const uploadImgs = async (index) => {
  const fileInfo: any = await trigerUpload();
  let files = fileInfo.target.files[0];
  if (
    files.type == "image/jpeg" ||
    files.type == "image/png" ||
    files.type == "image/jpg"
  ) {
    modalloading.value = true;
    trigerUploadObs(fileInfo)
      .then((res) => {
        form.value.imgs[index].url = res;
      })
      .finally(() => {
        modalloading.value = false;
      });
  } else {
    message.error("请上传jpeg、png、jpg类型的图片");
  }
};
//操作
const operation = (type: number, data?: any) => {
  if (type == 1) {
    //新建
    form.value = {isPermanent: true, status: 1, imgs: [], tagsIds: []};
    visible.value = true;
    title.value = "新建";
  } else if (type == 2) {
    //提交数据
    if (
      form.value.positionType == 3 ||
      form.value.positionType == 7 ||
      form.value.positionType == 8
    ) {
      //轮播图
      for (const item of form.value.imgs) {
        if (!item.url) {
          //图片没有添加
          return message.error("请补全展示图片！");
        }
      }
    }
    if (form.value.id) {
      formRef.value.validate().then(() => {
        let formData = JSON.parse(JSON.stringify(form.value));
        if (formData.isPermanent) {
          formData.endTime = null;
          formData.beginTime = null;
        }
        modalloading.value = true;
        //编辑
        if (formData.positionType == 4) {
          //限时优惠添加判断
          checkDuplicateSpecialOffer(formData)
            .then((res) => {
              if (res.data) {
                positionConfigUpdate(formData)
                  .then(() => {
                    message.success("编辑成功");
                    visible.value = false;
                    loadPagination();
                  })
                  .finally(() => {
                    modalloading.value = false;
                  });
              } else {
                Modal.confirm({
                  title:
                    "当前限时优惠的时间和原有数据有重叠，请确认是否继续当前操作!",
                  onOk() {
                    positionConfigUpdate(formData)
                      .then(() => {
                        message.success("编辑成功");
                        visible.value = false;
                        loadPagination();
                      })
                      .finally(() => {
                        modalloading.value = false;
                      });
                  }
                });
              }
            })
            .finally(() => {
              modalloading.value = false;
            });
        } else {
          positionConfigUpdate(formData)
            .then(() => {
              if (formData.positionType == 5 || formData.positionType == 9) {
                //需要更改标签
                positionConfigSetTag({
                  id: formData.id,
                  tagsIds: formData.tagsIds
                })
                  .then(() => {
                    message.success("编辑成功");
                    visible.value = false;
                    loadPagination();
                  })
                  .finally(() => {
                    modalloading.value = false;
                  });
              } else {
                message.success("编辑成功");
                visible.value = false;
                loadPagination();
                modalloading.value = false;
              }
            })
            .catch(() => {
              modalloading.value = false;
            });
        }
      });
    } else {
      formRef.value.validate().then(() => {
        let formData = JSON.parse(JSON.stringify(form.value));
        if (formData.isPermanent) {
          formData.endTime = null;
          formData.beginTime = null;
        }
        modalloading.value = true;
        //创建
        if (formData.positionType == 4) {
          //限时优惠添加判断
          checkDuplicateSpecialOffer(formData)
            .then((res) => {
              if (res.data) {
                positionConfigCreate(formData)
                  .then(() => {
                    message.success("创建成功");
                    visible.value = false;
                    loadPagination();
                  })
                  .finally(() => {
                    modalloading.value = false;
                  });
              } else {
                message.error("当前限时优惠的时间和原有数据有重叠,无法添加。");
                // Modal.confirm({
                //   title:
                //     "当前限时优惠的时间和原有数据有重叠，请确认是否继续当前操作!",
                //   onOk() {
                //     positionConfigCreate(formData)
                //       .then(() => {
                //         message.success("创建成功");
                //         visible.value = false;
                //         loadPagination();
                //       })
                //       .finally(() => {
                //         modalloading.value = false;
                //       });
                //   }
                // });
              }
            })
            .finally(() => {
              modalloading.value = false;
            });
        } else {
          positionConfigCreate(formData)
            .then(() => {
              message.success("创建成功");
              visible.value = false;
              loadPagination();
            })
            .finally(() => {
              modalloading.value = false;
            });
        }
      });
    }
  } else if (type == 3) {
    //编辑
    loading.value = true;
    positionConfigDetail({id: data.id})
      .then((res) => {
        form.value = res.data;
        if (!form.value.imgs) {
          form.value.imgs = [];
        }
        if (!form.value.tagsIds) {
          form.value.tagsIds = [];
        }
        getColumnsImgs();
        form.value.date = [form.value.beginTime, form.value.endTime];
        visible.value = true;
        title.value = "编辑";
      })
      .finally(() => {
        loading.value = false;
      });
  } else if (type == 4) {
    //删除
    Modal.confirm({
      title: "确定要删除该数据嘛",
      onOk() {
        loading.value = true;
        positionConfigDelete({id: data.id})
          .then((res) => {
            message.success("删除成功!");
            loadPagination(true);
          })
          .finally(() => {
            loading.value = false;
          });
      }
    });
  } else if (type == 5) {
    //状态
    let name = data.status == 1 ? "停用" : "启用";
    Modal.confirm({
      title: `确定要${name}该数据吗?`,
      onOk() {
        loading.value = true;
        positionConfigChangeStatus({
          id: data.id,
          status: data.status == 1 ? 0 : 1
        })
          .then((res) => {
            message.success("操作成功!");
            loadPagination(true);
          })
          .finally(() => {
            loading.value = false;
          });
      }
    });
  } else if (type == 6) {
    //关闭弹框
    formRef.value.clearValidate();
    visible.value = false;
  }
};
//删除图片
const operationDel = (index) => {
  Modal.confirm({
    title: "确定要删除该数据嘛",
    onOk() {
      form.value.imgs.splice(index, 1);
    }
  });
};
//获取数据
const loadPagination = (flag: boolean = false): void => {
  if (flag) {
    pageSet.value.pageNo = 1;
  }
  tableLoading.value = true;
  positionConfigPage(pageSet.value)
    .then((res) => {
      tableData.value = res.data.rows;
      tableData.value.forEach((item) => {
        if (!item.imgs) {
          item.imgs = [];
        }
      });
      pageSet.value.total = res.data.totalRows;
    })
    .finally(() => {
      tableLoading.value = false;
    });
};
//重置
const reset = (): void => {
  pageSet.value = {
    pageNo: 1,
    pageSize: 20,
    total: 0
  };
  loadPagination(true);
};
const columns = ref<Array<object>>([
  {
    title: "序号",
    dataIndex: "index",
    align: "center",
    width: 80,
    customRender: ({index}) => {
      return index + 1;
    }
  },
  {
    title: "位置名称",
    dataIndex: "positionName",
    align: "center",
    width: 200
  },
  {
    title: "位置类型",
    dataIndex: "positionType",
    align: "center",
    width: 200,
    customRender: ({value}) => {
      let name = "";
      positionType.value.forEach((item) => {
        if (item.value == value) {
          name = item.label;
        }
      });
      return name;
    }
  },
  {
    title: "展示图片",
    dataIndex: "img",
    align: "center",
    width: 150
  },
  {
    title: "是否永久",
    dataIndex: "isPermanent",
    align: "center",
    width: 100,
    customRender: ({value}) => {
      return value ? "是" : "否";
    }
  },
  {
    title: "开始结束时间",
    dataIndex: "sort",
    align: "center",
    width: 220,
    customRender: ({record}) => {
      if (record.isPermanent) {
        return "";
      } else {
        return (
          dayjs(record.beginTime).format("YYYY年MM月DD") +
          " 至 " +
          dayjs(record.endTime).format("YYYY年MM月DD")
        );
      }
    }
  },
  {
    title: "说明",
    dataIndex: "description",
    align: "center",
    width: 180
  },
  {
    title: "状态",
    dataIndex: "status",
    align: "center",
    width: 100,
    customRender: ({value}) => {
      return value ? "启用" : "停用";
    }
  },
  {
    title: "操作",
    dataIndex: "caozuo",
    align: "center",
    width: 200,
    fixed: "right"
  }
]);
const handleChange: TableProps["onChange"] = (
  pagination,
  filters,
  sorter
) => {};
const columnsImgs = ref<Array<object>>([
  {
    title: "展示图片",
    dataIndex: "url",
    align: "center",
    width: 200
  },
  {
    title: "图片跳转地址",
    dataIndex: "linkUrl",
    align: "center",
    width: 180
  },
  {
    title: "排序",
    dataIndex: "sort",
    align: "center",
    width: 80
    // defaultSortOrder: 'descend',
    // sorter: (a, b) => a.sort - b.sort,
  },
  {
    title: "操作",
    dataIndex: "caozuo",
    align: "center",
    width: 80,
    fixed: "right"
  }
]);
const getColumnsImgs = () => {
  if (form.value.positionType == 7 || form.value.positionType == 8) {
    columnsImgs.value = [
      {
        title: "展示图片",
        dataIndex: "url",
        align: "center",
        width: 200
      },
      {
        title: "图片跳转地址",
        dataIndex: "linkUrl",
        align: "center",
        width: 180
      },
      {
        title: "排序",
        dataIndex: "sort",
        align: "center",
        width: 80
        // defaultSortOrder: 'descend',
        // sorter: (a, b) => a.sort - b.sort,
      },
      {
        title: "操作",
        dataIndex: "caozuo",
        align: "center",
        width: 80,
        fixed: "right"
      }
    ];
  } else if (form.value.positionType == 3) {
    columnsImgs.value = [
      {
        title: "展示图片",
        dataIndex: "url",
        align: "center",
        width: 200
      },
      {
        title: "排序",
        dataIndex: "sort",
        align: "center",
        width: 80
        // defaultSortOrder: 'descend',
        // sorter: (a, b) => a.sort - b.sort,
      },
      {
        title: "操作",
        dataIndex: "caozuo",
        align: "center",
        width: 80,
        fixed: "right"
      }
    ];
  } else if (form.value.positionType == 5 || form.value.positionType == 9) {
    //选择标签
    pageSet1.value.name = "";
    loadPagination1(true);
  } else if (form.value.positionType == 4) {
    form.value.isPermanent = false;
    //限时优惠
  } else {
    columnsImgs.value = [];
  }
};
const addImgs = () => {
  form.value.imgs.unshift({
    sort: 0,
    url: "",
    linkUrl: ""
  });
};
//位置类型
const positionType = ref([
  {label: "精选分类", value: 1},
  {label: "推荐商品", value: 2},
  {label: "福礼采购", value: 3},
  {label: "限时优惠", value: 4},
  {label: "场景采购", value: 5},
  {label: "登录背景图", value: 6},
  {label: "首页展示图", value: 7},
  {label: "首页广告图", value: 8},
  {label: "热销", value: 9}
]);
function changePicker(a, b) {
  if (a) {
    form.value.beginTime = b[0];
    form.value.endTime = b[1];
  } else {
    form.value.beginTime = null;
    form.value.endTime = null;
  }
}
const sortRank = () => {
  form.value.imgs.sort((a, b) => a.sort - b.sort);
};
const columns1 = ref([
  {
    title: "序号",
    dataIndex: "name",
    align: "center",
    width: 50,
    customRender: ({index}) => {
      return index + 1;
    },
    fixed: "left"
  },
  {
    title: "名称",
    dataIndex: "name",
    align: "center",
    width: 400
  }
]);
const tableData1: any = ref([]);
const onSelectChange = (e) => {
  form.value.tagsIds = e;
};
const tableLoading1 = ref(false);
const pageSet1 = ref({
  pageNo: 1,
  pageSize: 20,
  total: 0,
  tagType: 2,
  name: ""
});
const loadPagination1 = (flag: boolean = false): void => {
  if (flag) {
    pageSet1.value.pageNo = 1;
  }
  tableLoading1.value = true;
  tagsInfoPage(pageSet1.value)
    .then((res) => {
      tableData1.value = res.data.rows;
      pageSet1.value.total = res.data.totalRows;
    })
    .finally(() => {
      tableLoading1.value = false;
    });
};
loadPagination(true);
</script>
<style lang="less" scoped></style>
